package be.nvlooy.moviereminder.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import be.nvlooy.moviereminder.entities.User;
import be.nvlooy.moviereminder.service.UserService;

@Service
public class SecurityFacade {
	
	private UserService userService;
	
	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public boolean isLoggedIn() {
		if(SecurityContextHolder.getContext().getAuthentication() != null &&
				SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof UserDetails)
			return true;
		else 
			return false;
	}
	
	public User getAuthenticatedUser() {
		if(isLoggedIn()) {
			UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			return userService.findByUserName(userDetails.getUsername());
		}
		else 
			return null;
	}
	
}
